﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;

namespace MainClient
{
    public partial class MainWindow : Form
    {
        private Color colorAvailable = Color.Blue;
        private Color colorOrdering = Color.Orange;
        private Color colorOrdered = Color.DarkRed;
        private Color colorPaid = Color.Green;

        private ButtonEX selectedBtn;

        public MainWindow(string operator1, string permission)
        {
            InitializeComponent();
            this.cb_tableType.SelectedIndex = 0;   // Default select "全部" to show all tables.
            timer1.Start();   // Start timer to display current time.

            this.tssl_operator.Text = operator1;
            // Init permission of this user.
            // To do handle...
            selectedBtn = null;
        }

        /**
         * Create new button which will be added into gb_tables.
         */
        private Button createTableBtn()
        {
            ButtonEX btn1 = new ButtonEX();
            btn1.FlatStyle = FlatStyle.Flat;
            btn1.ForeColor = Color.White;
            btn1.Font = new Font("Microsoft YaHei", 9, FontStyle.Regular);
            btn1.FlatAppearance.BorderSize = 3;
            btn1.FlatAppearance.BorderColor = Color.Silver;
            btn1.Size = new Size(77, 77);

            // Add EventListener
            btn1.MouseClick += new MouseEventHandler(this.btn_table_MouseClick);
            btn1.DoubleClick += new System.EventHandler(this.btn_table_DoubleClick);
            return btn1;
        }
        /**
         * Load imformation of tables from db.
         */
        private void loadTablesData()
        {
            // Get mount of tables from db.
            DataAccess.TableDAO tableDAO = new DataAccess.TableDAO();
            DataSet result = tableDAO.getTables(this.cb_tableType.SelectedIndex, 0);
            // Per row show how many buttons.
            int percount = (Int32) (this.gb_tables.Width / 80);

            int loop = result.Tables[0].Rows.Count - this.gb_tables.Controls.Count;
            // Add new table buttons.
            while (loop > 0) {
                Button btn1 = createTableBtn();
                this.gb_tables.Controls.Add(btn1);
                loop --;
            }
            // Remove the last table button.
            while (loop < 0) {
                this.gb_tables.Controls.RemoveAt(this.gb_tables.Controls.Count-1);
                loop ++;
            }

            int idle = 0;
            int ordering = 0;
            int ordered = 0;
            int paid = 0;
            int i = 0;
            // Set information of all tables.
            foreach(DataRow item in result.Tables[0].Rows)
            {
                Button btn1 = (Button)this.gb_tables.Controls[i];
                btn1.Name = item["tableName"].ToString();
                btn1.Text = item["tableName"].ToString();
                if (percount == 0) // Stands for the window do not display. So not flush data.
                {
                    return;
                }
                int x = 5 + 80 * (i % percount);
                int y = 15 + 80 * (i / percount);
                btn1.Location = new Point(x, y);
                int tableState = Int32.Parse(item["tableState"].ToString());
                switch (tableState) {
                    case DataAccess.TableDAO.STATE_AVAILABLE:    // Free table
                        btn1.BackColor = colorAvailable;
                        idle++;
                        break;
                    case DataAccess.TableDAO.STATE_ORDERING:     // Have custom in that table
                        btn1.BackColor = colorOrdering;
                        ordering++;
                        break;
                    case DataAccess.TableDAO.STATE_ORDERED:    // Payed table
                        btn1.BackColor = colorOrdered;
                        ordered++;
                        break;
                    case DataAccess.TableDAO.STATE_PAID:    // Reserve table
                        btn1.BackColor = colorPaid;
                        paid++;
                        break;
                    default:
                        btn1.BackColor = Color.Silver;
                        break;
                }
                i += 1;
            }
            this.lbl_idle.Text = idle.ToString();
            this.lbl_ordering.Text = ordering.ToString();
            this.lbl_ordered.Text = ordered.ToString();
            this.lbl_paid.Text = paid.ToString();
        }

        #region Handle Table Buttons operations.
        private void btn_table_MouseClick(object sender, MouseEventArgs e)
        {
            ButtonEX btn1 = (ButtonEX)sender;
            // Clear old button border color, Then set new button border color.
            if (selectedBtn != null)
                selectedBtn.FlatAppearance.BorderColor = Color.Silver;
            this.selectedBtn = btn1;
            btn1.FlatAppearance.BorderColor = Color.Red;
            this.showTableBasicInfo(btn1.Name);
        }

        private void btn_table_DoubleClick(object sender, EventArgs e)
        {
            ButtonEX btn1 = (ButtonEX)sender;
            DataAccess.TableDAO tableDAO = new DataAccess.TableDAO();
            if (btn1.BackColor == colorAvailable)    // available
            {
                frmKaitai frm1 = new frmKaitai(
                                                            this.tssl_operator.Text.Trim(),
                                                            this.tb_tableID.Text.Trim(),
                                                            this.lbl_info_type.Text.Trim(),
                                                            this.lbl_info_num.Text.Trim(),
                                                            this.lbl_tablePrice.Text.Trim());
                frm1.ShowDialog();
            }
            else if (btn1.BackColor == colorOrdering) // ordering
            {
                frmDiancai frm2 = new frmDiancai(
                                                            this.tssl_operator.Text.Trim(),
                                                            this.tb_tableID.Text.Trim(),
                                                            this.tb_orderID.Text.Trim());
                frm2.Owner = this;
                frm2.ShowDialog();
            }
            else if (btn1.BackColor == colorOrdered) // ordered
            {
                frmJiezhang frm3 = new frmJiezhang(LoginUser.getCurrOper(),
                                        this.tb_orderID.Text.Trim(),
                                        this.tb_tableID.Text.Trim());
                frm3.ShowDialog();
            }
            else if (btn1.BackColor == colorPaid) // payed table
            {
                string strShow = "是否进行清台操作？";
                if (MessageBox.Show(strShow,
                                                                   "提示",
                                                                   MessageBoxButtons.OKCancel,
                                                                   MessageBoxIcon.Exclamation) == DialogResult.OK)
                {
                    try
                    {
                        tableDAO.setTableState(this.tb_tableID.Text.Trim(),
                                DataAccess.TableDAO.STATE_AVAILABLE);
                        DataAccess.OrderDAO orderDAO = new DataAccess.OrderDAO();
                        orderDAO.setOrderState(this.tb_orderID.Text.Trim(), DataAccess.OrderDAO.ORDER_STATE_HISTORY);
                    }
                    catch (Exception e1)
                    {
                        strShow = "操作失败，请稍后再试！";
                        MessageBox.Show(strShow, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        Console.WriteLine(e1.Message);
                    }
                }
            }
            else
            {
                throw new Exception("获取桌位状态失败！");
            }
            tableDAO = null;
        }
        #endregion

        private void showTableBasicInfo(string tableName)
        {
            this.tb_tableID.Text = tableName;
            DataAccess.TableDAO tableDao = new DataAccess.TableDAO();
            Hashtable info = (Hashtable)tableDao.getTableBasicInfo(tableName);
            this.lbl_info_type.Text = this.getTableType(Int32.Parse(info["tableType"].ToString()));
            this.lbl_tablePrice.Text = info["tablePrice"].ToString();
            this.lbl_info_num.Text = info["num"].ToString();

            showTableExtendInfo(tableName);
        }

        private void showTableExtendInfo(string tableName)
        {
            // Clear old datas.
            this.tb_orderID.Text = "";
            this.lbl_info_waiterID.Text = "";
            this.lbl_info_sum.Text = "";

            DataAccess.TableDAO tableDAO = new DataAccess.TableDAO();
            Hashtable info = (Hashtable)tableDAO.getTableAdvInfo(tableName);
            if (info.Count > 0)
            {
                this.tb_orderID.Text = info["orderID"].ToString();
                //this.lbl_info_orderTime.Text = info["orderTime"].ToString();
                this.lbl_info_waiterID.Text = info["waiterID"].ToString();
                this.lbl_info_sum.Text = info["totalPrice"].ToString();
            }
            DataAccess.OrderDAO orderDAO = new DataAccess.OrderDAO();
            DataSet ds = orderDAO.loadOrderItems(this.tb_orderID.Text.Trim());
            this.dataGridView1.DataSource = ds.Tables[0].DefaultView;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            this.tssl_currtime.Text = DateTime.Now.ToString();

            loadTablesData();

        }

        private void TSMI_About_Click(object sender, EventArgs e)
        {
            AboutMe ab = new AboutMe();
            ab.ShowDialog();
        }

        private void TSMI_LockSystem_Click(object sender, EventArgs e)
        {
            frmLockSystem locksystem = new frmLockSystem(this.tssl_operator.Text.Trim());
            locksystem.Owner = this;
            locksystem.ShowDialog();
        }

        private void cb_tableType_SelectedIndexChanged(object sender, EventArgs e)
        {
            loadTablesData();
        }

        private void MainWindow_SizeChanged(object sender, EventArgs e)
        {
            //loadTablesData();
        }

        // Get table type through number.
        private string getTableType(int i)
        {
            switch (i)
            {
                case 1:
                    return "大厅";
                case 2:
                    return "普通包厢";
                case 3:
                    return "高级包厢";
                case 4:
                    return "VIP包厢";
                default:
                    return "";
            }
        }

        private void MainWindow_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }

        private void MainWindow_FormClosing(object sender, FormClosingEventArgs e)
        {
            string strShow = "确定退出本系统吗？";
            e.Cancel = !(MessageBox.Show(strShow,
                                                               "提示",
                                                               MessageBoxButtons.OKCancel,
                                                               MessageBoxIcon.Exclamation) == DialogResult.OK);
        }

        // 桌位设置
        private void tssl_zwsz_Click(object sender, EventArgs e)
        {
            frmTableManager frmD = new frmTableManager();
            frmD.Show();
        }

        // 酒菜设置
        private void tsmi_JCSZ_Click(object sender, EventArgs e)
        {
            frmMenuManager frmD = new frmMenuManager();
            frmD.Show();
        }

        // 员工管理
        private void tsmi_YGGL_Click(object sender, EventArgs e)
        {
            frmStaffManager frmD = new frmStaffManager();
            frmD.Show();
        }

        // 数据备份
        private void tsmi_SJBF_Click(object sender, EventArgs e)
        {
            //frmBackupDB frmD = new frmBackupDB();
            //frmD.ShowDialog();
        }

        // 数据恢复
        private void tsmi_SJFF_Click(object sender, EventArgs e)
        {
            //frmRecoveryDB frmD = new frmRecoveryDB();
            //frmD.ShowDialog();
        }

        private void tsmi_tcxt_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void tsmi_CloseAccount_Click(object sender, EventArgs e)
        {
            if (selectedBtn != null && selectedBtn.BackColor == colorOrdered) // inuse table
            {
                string strOrderID = this.tb_orderID.Text.Trim();
                // Judge whether this orderID is submit.
                DataAccess.OrderDAO orderDAO = new DataAccess.OrderDAO();
                if (!orderDAO.isOrderSubmit(strOrderID))
                {
                    string strShow = "订单:" + strOrderID + " 未提交, 无法结账!";
                    MessageBox.Show(strShow, "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                frmJiezhang jieZhang = new frmJiezhang(
                                this.tssl_operator.Text.Trim(),
                                strOrderID,
                                this.tb_tableID.Text.Trim());
                jieZhang.ShowDialog();
            }
            else
            {
                MessageBox.Show("所选桌位非在使用状态，无法结帐！",
                                "警告",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Warning);
            }
        }
    } // end of class
}  
